<template>
  <el-dialog 
    title="快速分配柜组和POS" 
    :visible.sync="dialogVisible" 
    width="1000px" 
    append-to-body
    @close="handleClose"
  >
    <div class="quick-assign">
      <el-row :gutter="20">
        <!-- 收银员信息 -->
        <el-col :span="8">
          <el-card header="收银员信息">
            <div class="cashier-info">
              <div class="info-item">
                <label>收银员编码：</label>
                <span>{{ cashierData.cashierCode }}</span>
              </div>
              <div class="info-item">
                <label>收银员姓名：</label>
                <span>{{ cashierData.cashierName }}</span>
              </div>
              <div class="info-item">
                <label>联系电话：</label>
                <span>{{ cashierData.phone }}</span>
              </div>
              <div class="info-item">
                <label>当前状态：</label>
                <dict-tag :options="dict.type.sys_normal_disable" :value="cashierData.status"/>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <!-- 柜组分配 -->
        <el-col :span="8">
          <el-card header="柜组分配">
            <div class="assign-section">
              <div class="section-header">
                <span>可分配柜组</span>
                <el-button size="mini" type="text" @click="selectAllGroups">全选</el-button>
              </div>
              <el-checkbox-group v-model="selectedGroups" @change="handleGroupChange">
                <div class="checkbox-list">
                  <el-checkbox 
                    v-for="group in availableGroups" 
                    :key="group.groupId"
                    :label="group.groupId"
                    :disabled="group.status === '1'"
                  >
                    <div class="checkbox-item">
                      <span class="group-name">{{ group.groupName }}</span>
                      <el-tag size="mini" type="info">{{ group.groupCode }}</el-tag>
                      <div class="group-info">
                        <span class="device-count">{{ group.deviceCount || 0 }}台POS</span>
                        <span class="cashier-count">{{ group.cashierCount || 0 }}人</span>
                      </div>
                    </div>
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </el-card>
        </el-col>
        
        <!-- POS设备分配 -->
        <el-col :span="8">
          <el-card header="POS设备分配">
            <div class="assign-section">
              <div class="section-header">
                <span>可分配POS</span>
                <el-button size="mini" type="text" @click="selectAllDevices">全选</el-button>
              </div>
              <el-checkbox-group v-model="selectedDevices" @change="handleDeviceChange">
                <div class="checkbox-list">
                  <el-checkbox 
                    v-for="device in availableDevices" 
                    :key="device.deviceId"
                    :label="device.deviceId"
                    :disabled="device.status === '1'"
                  >
                    <div class="checkbox-item">
                      <span class="device-name">{{ device.deviceName }}</span>
                      <el-tag size="mini" type="info">{{ device.deviceCode }}</el-tag>
                      <div class="device-info">
                        <dict-tag :options="dict.type.pos_device_type" :value="device.deviceType" size="mini"/>
                        <span class="device-status" :class="device.status === '0' ? 'online' : 'offline'">
                          {{ device.status === '0' ? '在线' : '离线' }}
                        </span>
                      </div>
                    </div>
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 分配预览 -->
      <el-row style="margin-top: 20px;">
        <el-col :span="24">
          <el-card header="分配预览">
            <div class="preview-section">
              <div class="preview-item">
                <label>已选择柜组：</label>
                <div class="selected-items">
                  <el-tag 
                    v-for="groupId in selectedGroups" 
                    :key="groupId"
                    closable
                    @close="removeGroup(groupId)"
                    style="margin-right: 8px; margin-bottom: 8px;"
                  >
                    {{ getGroupName(groupId) }}
                  </el-tag>
                  <span v-if="selectedGroups.length === 0" class="empty-text">未选择柜组</span>
                </div>
              </div>
              <div class="preview-item">
                <label>已选择POS：</label>
                <div class="selected-items">
                  <el-tag 
                    v-for="deviceId in selectedDevices" 
                    :key="deviceId"
                    closable
                    @close="removeDevice(deviceId)"
                    style="margin-right: 8px; margin-bottom: 8px;"
                  >
                    {{ getDeviceName(deviceId) }}
                  </el-tag>
                  <span v-if="selectedDevices.length === 0" class="empty-text">未选择POS</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">保存分配</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listGroup } from "@/api/pos/group";
import { listDevice } from "@/api/pos/device";
import { setCashierGroups, setCashierDevices } from "@/api/pos/cashier";

export default {
  name: "QuickAssign",
  dicts: ['sys_normal_disable', 'pos_device_type'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    cashierData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      dialogVisible: false,
      saving: false,
      // 可用数据
      availableGroups: [],
      availableDevices: [],
      // 已选择的数据
      selectedGroups: [],
      selectedDevices: []
    };
  },
  watch: {
    visible(val) {
      this.dialogVisible = val;
      if (val) {
        this.loadData();
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val);
    }
  },
  methods: {
    /** 加载数据 */
    async loadData() {
      await Promise.all([
        this.loadAvailableGroups(),
        this.loadAvailableDevices()
      ]);
      // 加载当前收银员已分配的柜组和POS
      this.loadCurrentAssignments();
    },
    
    /** 加载可用柜组 */
    async loadAvailableGroups() {
      try {
        const response = await listGroup({ status: '0' });
        this.availableGroups = response.rows || [];
      } catch (error) {
        this.$modal.msgError("加载可用柜组失败");
      }
    },
    
    /** 加载可用POS设备 */
    async loadAvailableDevices() {
      try {
        const response = await listDevice({ status: '0' });
        this.availableDevices = response.rows || [];
      } catch (error) {
        this.$modal.msgError("加载可用POS设备失败");
      }
    },
    
    /** 加载当前分配情况 */
    loadCurrentAssignments() {
      // 这里应该从props中获取当前收银员已分配的柜组和POS
      // 暂时使用空数组，实际应该从父组件传入
      this.selectedGroups = this.cashierData.managedGroups || [];
      this.selectedDevices = this.cashierData.availableDevices || [];
    },
    
    /** 全选柜组 */
    selectAllGroups() {
      const enabledGroups = this.availableGroups.filter(group => group.status === '0');
      this.selectedGroups = enabledGroups.map(group => group.groupId);
    },
    
    /** 全选POS设备 */
    selectAllDevices() {
      const enabledDevices = this.availableDevices.filter(device => device.status === '0');
      this.selectedDevices = enabledDevices.map(device => device.deviceId);
    },
    
    /** 柜组选择变化 */
    handleGroupChange(value) {
      // 可以在这里添加一些逻辑，比如自动选择该柜组下的POS设备
    },
    
    /** POS设备选择变化 */
    handleDeviceChange(value) {
      // 可以在这里添加一些逻辑
    },
    
    /** 移除柜组 */
    removeGroup(groupId) {
      const index = this.selectedGroups.indexOf(groupId);
      if (index > -1) {
        this.selectedGroups.splice(index, 1);
      }
    },
    
    /** 移除POS设备 */
    removeDevice(deviceId) {
      const index = this.selectedDevices.indexOf(deviceId);
      if (index > -1) {
        this.selectedDevices.splice(index, 1);
      }
    },
    
    /** 获取柜组名称 */
    getGroupName(groupId) {
      const group = this.availableGroups.find(g => g.groupId === groupId);
      return group ? group.groupName : '';
    },
    
    /** 获取POS设备名称 */
    getDeviceName(deviceId) {
      const device = this.availableDevices.find(d => d.deviceId === deviceId);
      return device ? device.deviceName : '';
    },
    
    /** 保存分配 */
    async handleSave() {
      if (this.selectedGroups.length === 0 && this.selectedDevices.length === 0) {
        this.$modal.msgWarning("请至少选择一个柜组或POS设备");
        return;
      }
      
      this.saving = true;
      try {
        // 保存柜组分配
        if (this.selectedGroups.length > 0) {
          await setCashierGroups(this.cashierData.cashierId, this.selectedGroups);
        }
        
        // 保存POS设备分配
        if (this.selectedDevices.length > 0) {
          await setCashierDevices(this.cashierData.cashierId, this.selectedDevices);
        }
        
        this.$modal.msgSuccess("分配保存成功");
        this.$emit('refresh');
        this.handleClose();
      } catch (error) {
        this.$modal.msgError("分配保存失败");
      } finally {
        this.saving = false;
      }
    },
    
    /** 关闭对话框 */
    handleClose() {
      this.dialogVisible = false;
      this.selectedGroups = [];
      this.selectedDevices = [];
    }
  }
};
</script>

<style scoped>
.quick-assign {
  padding: 10px 0;
}

.cashier-info {
  padding: 10px 0;
}

.info-item {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}

.info-item label {
  width: 80px;
  color: #606266;
  font-weight: 500;
}

.assign-section {
  height: 400px;
  overflow-y: auto;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.section-header span {
  font-weight: 600;
  color: #303133;
}

.checkbox-list {
  max-height: 350px;
  overflow-y: auto;
}

.checkbox-item {
  display: flex;
  flex-direction: column;
  padding: 8px 0;
  border-bottom: 1px solid #f5f7fa;
}

.checkbox-item:last-child {
  border-bottom: none;
}

.group-name,
.device-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.group-info,
.device-info {
  display: flex;
  gap: 8px;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.device-count,
.cashier-count {
  background: #f0f9ff;
  color: #1890ff;
  padding: 2px 6px;
  border-radius: 3px;
}

.device-status.online {
  color: #67c23a;
}

.device-status.offline {
  color: #f56c6c;
}

.preview-section {
  padding: 15px 0;
}

.preview-item {
  margin-bottom: 20px;
}

.preview-item label {
  display: block;
  margin-bottom: 10px;
  font-weight: 600;
  color: #303133;
}

.selected-items {
  min-height: 40px;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fafafa;
}

.empty-text {
  color: #c0c4cc;
  font-style: italic;
}

.dialog-footer {
  text-align: right;
}
</style>
